import { sign, verify } from 'jsonwebtoken'

// 密钥
const secret = '123456'

/**
 * 检测并解析token
 * @param token token
 * @returns
 */
export const parseToken = (token: string): any | string => {
    try {
        const payload = verify(token, secret)
        return payload
    } catch (error) {
        throw new Error('token解析失败')
    }
}

/**
 * 生成token
 * @param payload 载荷
 * @returns
 */
export const generateToken = (payload: {
    username: string
    id: number
}): string => {
    const token = sign(payload, secret, { expiresIn: '1d' })
    return token
}
